package com.yaha.controler.devices;

import java.util.ArrayList;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.yaha.controler.MyApplication;
import com.yaha.controler.db.interfaces.impl.DeviceHistoryListImpl;
import com.yaha.controler.devices.interfaces.DeviceStateListener;
import com.yaha.controler.devices.pojo.MdnsDevice;
import com.yaha.controler.utils.MyLog;

public class DeviceManager {

	private static final String TAG = DeviceManager.class.getSimpleName();
	private static DeviceManager mDeviceManager;

	private ArrayList<DeviceStateListener> deviceStateListenerList;
	/**
	 * Mdns设备列表
	 */
	private ArrayList<MdnsDevice> mMdnsList = new ArrayList<MdnsDevice>();
	/** 选中MdnsDevice */
	private MdnsDevice choiceMdnsDevice = null;

	private DeviceManager() {

	}

	public static DeviceManager newInstance() {
		if (null == mDeviceManager) {
			mDeviceManager = new DeviceManager();
		}
		return mDeviceManager;
	}

	public MdnsDevice getChoiceMdnsDevice() {
		return choiceMdnsDevice;
	}

	// ----------------设置和获取Mdns设备--Begin-----------------------------------------------------------
	public void setChoiceMdnsDevice(MdnsDevice choiceMdnsDevice) {
		this.choiceMdnsDevice = choiceMdnsDevice;
		if (null == choiceMdnsDevice) {
			MyLog.e(TAG, "ChoiceMdnsDevice is null!!!");
		} else {
			// 保存选中的Mdns设备相关信息
			saveDeviceConnectInfo(MyApplication.getAppContext(), choiceMdnsDevice.getName(), MyApplication.curWifiSSID);
		}
		// 为设备添加监听器
		if (null != deviceStateListenerList && deviceStateListenerList.size() > 0) {
			for (DeviceStateListener listener : deviceStateListenerList) {
				listener.onChioseDevice(choiceMdnsDevice);
			}
		}
		Log.d(TAG, "setChoiceMdnsDevicee==" + choiceMdnsDevice);
		// 更新 device 选中状态
		MyApplication.eventBus.post(DeviceConstants.EVENTBUS_DEV_SEL_STATE_UPDATE);
		// 通知更新设备更新
		MyApplication.eventBus.post(DeviceConstants.EVENTBUS_DEVICE_UPDATE);
	}

	// -----------------设置和获取Mdns设备--End----------------------------------------------------------------
	/**
	 * <功能描述>增加设备监听器
	 * 
	 * @param deviceStateListener
	 */
	public void addDeviceStateListener(DeviceStateListener deviceStateListener) {
		if (null == deviceStateListenerList) {
			deviceStateListenerList = new ArrayList<DeviceStateListener>();
		}
		if (!deviceStateListenerList.contains(deviceStateListener)) {
			deviceStateListenerList.add(deviceStateListener);
		}
	}

	/**
	 * <功能描述>移除设备监听器
	 * 
	 * @param deviceStateListener
	 */
	public void removeDeviceStateListener(DeviceStateListener deviceStateListener) {
		if (null != deviceStateListenerList && deviceStateListenerList.contains(deviceStateListener)) {
			deviceStateListenerList.remove(deviceStateListener);
		}
	}

	// ------------------------增加Mdns设备，移除Mdns设备操作--Begin---------------------------------------
	/**
	 * <功能描述>添加Mdns设备
	 * 
	 * @param mdnsDevice
	 * @return
	 */
	public synchronized boolean addMdnsDevice(MdnsDevice mdnsDevice) {
		boolean isAdd = false;
		if (null == this.mMdnsList) {
			mMdnsList = new ArrayList<MdnsDevice>();
		}
		if (null != mdnsDevice) {
			if (mMdnsList.isEmpty()) {
				isAdd = mMdnsList.add(mdnsDevice);
			} else {
				String mac = mdnsDevice.getMac();
				String ip = mdnsDevice.getIp();
				String name = mdnsDevice.getName();

				ArrayList<MdnsDevice> removeMdnsList = new ArrayList<MdnsDevice>();
				// 对比设备列表中的设备去掉重复的设备之后添加
				if (TextUtils.isEmpty(mac)) {
					for (MdnsDevice dev : mMdnsList) {
						if (null != name && null != ip && name.equals(dev.getName()) && ip.equals(dev.getIp())) {
							removeMdnsList.add(dev);
						}
					}
					mMdnsList.removeAll(removeMdnsList);
					isAdd = mMdnsList.add(mdnsDevice);
				} else {
					for (MdnsDevice dev : mMdnsList) {
						if (mac.equals(dev.getMac()) && null != ip && ip.equals(dev.getIp())) {
							removeMdnsList.add(dev);
						}
					}
					mMdnsList.removeAll(removeMdnsList);
					isAdd = mMdnsList.add(mdnsDevice);
				}
			}
		}
		if (isAdd) {
			// 通知更新设备更新
			MyApplication.eventBus.post(DeviceConstants.EVENTBUS_DEVICE_UPDATE);
		}
		return isAdd;
	}

	/**
	 * 移出一个mdns设备 mac 1:不为空怎以mac为标识 2:空则以ip和name为标识 TODO
	 * 
	 * @param mdnsDevice
	 */
	public synchronized boolean removeMdnsDevice(MdnsDevice mdnsDevice) {

		boolean isremove = false;

		if (null != mMdnsList && mMdnsList.size() > 0 && null != mdnsDevice) {

			String name = mdnsDevice.getName();
			String ip = mdnsDevice.getIp();
			String mac = mdnsDevice.getMac();

			ArrayList<MdnsDevice> removeList = new ArrayList<MdnsDevice>();
			if (TextUtils.isEmpty(mac)) {

				for (MdnsDevice dev : mMdnsList) {
					if (null != name && name.equals(dev.getMac()) && null != ip && ip.equals(dev.getIp())) {
						removeList.add(dev);
					}
				}
				isremove = mMdnsList.removeAll(removeList);

			} else {

				for (MdnsDevice dev : mMdnsList) {
					if (mac.equals(dev.getMac()) && null != ip && ip.equals(dev.getIp())) {
						removeList.add(dev);
					}
				}
				isremove = mMdnsList.removeAll(removeList);
			}
		}

		if (isremove) {
			// 通知更新设备更新
			MyApplication.eventBus.post(DeviceConstants.EVENTBUS_DEVICE_UPDATE);
		}

		return isremove;
	}

	// ------------------------增加Mdns设备，移除Mdns设备操作--End---------------------------------------

	/**
	 * <功能描述>判断是不是最后连接的设备，如果是最后连接的设备直接连接上，如果不是跳过
	 * 
	 * @param mContext
	 * @param mdnsDevice
	 * @param curWifiSSID
	 */
	public synchronized void connectHistoryDevice(Context context, MdnsDevice device, String wifiName) {
		MdnsDevice dev = getChoiceMdnsDevice();
		Log.d(TAG, "connectHistoryDevice choiceDev-> " + dev);
		// 先判断是否有历史连接的当前的设备，有就连接上，没有连接当前发现的设备
		if (null == dev) {
			DeviceHistoryListImpl deviceHistoryListImpl = new DeviceHistoryListImpl(context);
			if (deviceHistoryListImpl.hasHistoryInWifi(wifiName)) {
				if (null != device && deviceHistoryListImpl.isLastConnectDevice(wifiName, device.getName())) {
					Log.d(TAG, "connectHistoryDevice device 1= " + device.getName());
					// 设置选中当前的设备
					setChoiceMdnsDevice(device);
				}
			} else {
				Log.d(TAG, "connectHistoryDevice new device = " + device.getName());
				if (null != device) {
					// 设置选中当前的设备
					setChoiceMdnsDevice(device);
				}
			}
			deviceHistoryListImpl.close();
		}
	}

	/**
	 * <功能描述>保存设备连接记录
	 * 
	 * @param appContext
	 *            应用上下文对象
	 * @param name
	 *            设备名称
	 * @param curWifiSSID
	 *            Wifiname
	 */
	private void saveDeviceConnectInfo(Context context, String deviceName, String wifiName) {
		DeviceHistoryListImpl deviceHistoryListImpl = new DeviceHistoryListImpl(context);

		int count = deviceHistoryListImpl.getDeviceConnectCount(deviceName, wifiName);
		if (count > 0) {
			boolean isUpdate = deviceHistoryListImpl
					.update(deviceName, wifiName, System.currentTimeMillis(), count + 1);
			Log.d(TAG, "saveDeviceConnectInfo update [wifiName:" + wifiName + "], [deviceName:" + deviceName
					+ "] ret : " + isUpdate);
		} else {
			long raw = deviceHistoryListImpl.insert(deviceName, wifiName, System.currentTimeMillis(), count + 1);
			Log.d(TAG, "saveDeviceConnectInfo insert [wifiName:" + wifiName + "], [deviceName:" + deviceName
					+ "] ret : " + raw);
		}
		deviceHistoryListImpl.close();
	}

}
